package xyz.csmcool.imoss.service.impl;

import com.obs.services.ObsClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import xyz.csmcool.imoss.config.UploadTypeEnum;
import xyz.csmcool.imoss.entity.OssConfig;
import xyz.csmcool.imoss.mapper.OssConfigMapper;
import xyz.csmcool.imoss.service.UploadFile;
import xyz.csmcool.imoss.utils.NameUtil;

import java.io.File;
import java.io.IOException;

/**
 * @author 什锦
 * @Package xyz.csmcool.imoss.service.impl
 * @since 2022/8/5 14:34
 */

@Component
@RequiredArgsConstructor
public class HuaweiUpload implements UploadFile {

    final OssConfigMapper ossConfigMapper;

    @Override
    public UploadTypeEnum getUploadType() {
        return UploadTypeEnum.HUAWEI;
    }


    @Override
    public String upload(File file, String prefix2) {
        OssConfig ossConfig = ossConfigMapper.selectConfig();

        String endPoint = "https://your-endpoint";
        String ak = "*** Provide your Access Key ***";
        String sk = "*** Provide your Secret Key ***";
        String prefix = "img/";

        try {
            endPoint = ossConfig.getRegion();
            ak = ossConfig.getSecretId();
            sk = ossConfig.getSecretKey();

            prefix = ossConfig.getPrefix();
            String fileName = prefix + prefix2 + NameUtil.generateUniqueName(file.getName());

            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            obsClient.putObject(ossConfig.getBucketName(), fileName, file);
            obsClient.close();
            return "https://" + ossConfig.getUrl() + "/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
